package com.book.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/addbook")
public class addbook extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doPost(req, resp);
    }
    @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String id2 = req.getParameter("id2");
        String name = req.getParameter("name");
        String author = req.getParameter("author");
        String type = req.getParameter("type");
        String photo = req.getParameter("photo");
        String content = req.getParameter("content");
        try {
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/library?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true","root","1234");
            String sql = "INSERT INTO library.book(id,name,author,type,photo,content) VALUES(?,?,?,?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, id2);
            ps.setString(2, name);
            ps.setString(3, author);
            ps.setString(4, type);
            ps.setString(5, photo);
            ps.setString(6, content);
            ps.executeUpdate();
            resp.setContentType("text/html;charset=utf-8");
            req.getRequestDispatcher("/successadd.jsp").forward(req, resp);
            rs.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                if(rs != null){
                    rs.close();
                }
                if(ps!=null){
                    ps.close();
                }
                if(conn!=null){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}